import {
  isAndroid,
  isIOS,
  isTencentWebview,
  getQueryParamByName,
  getBrowserType,
  BROWSER,
  DomUtil,
  catchGlobalError,
  uploadErrorInfo,
  onloadImage,
  getCacheUUID,
  fileUrlHandled,
  isNeedWebClip,
  isNeedKeFuWebClip,
  getEnTitleName,
  isAppUpdate,
  urlAddParam,
} from '@/common/js/common';
import ua2obj from 'ua2obj';
import { Base64 } from 'js-base64';
import * as qs from 'qs';
import queryString from 'query-string';
import ClipboardJS from 'clipboard';
import Swiper from 'swiper/dist/js/swiper.min.js';
import 'swiper/dist/css/swiper.min.css';
import '@/common/phpFile/css/ba.css';
import '../style/download-h5.scss';
import '../style/animate.css';
import request from '../js/request';
import ProgressBar from 'progressbar.js';
import { nameConfig } from '@theme/vm';
import $ from 'jquery';
const SITE_NAME = process.env.SITE_NAME || '';
const imgPath = SITE_NAME + '_appdown';
const defWebClipUrl = '/api/findmed/v2/member/webclip/download';
let webClipPreUrl = defWebClipUrl;
// 这里的桌面客服的下载地址是  当前域名 + defKefuWebClipUrl 再 拼接 ?url=xxx&siteCode=xx, xxx 是 preInfo接口的 _webclip_book_mark
const defKefuWebClipApi = '/api/findmed/v2/member/webclip/customer/download';
const ModalType = {
  iosNoSafari: 'iosNoSafari',
  ios: 'ios',
  android: 'android',
};

catchGlobalError();

export default function (appKey: string, type: 'sport' | 'site') {
  const isSport = type === 'sport';
  const i_code: any = getQueryParamByName('i_code');
  const r_code = getQueryParamByName('r_code');
  let isCustomer = getQueryParamByName('isCustomer');
  let app_android_download = '';
  let app_ios_download = '';
  const ios_download = nameConfig.ios_download; // ios线上包地址
  const android_download = nameConfig.android_download; // 安卓线上包地址
  let android_webclip_book_mark = ''; // 安卓客服webclip书签
  let ios_webclip_book_mark = ''; // ios客服 webclip书签
  const domainHost = window.location.host;

  let h5_domain = nameConfig.h5_domain;
  let locationIp = '';
  let ipAddress = '';
  let isCustomerClick = false;
  let customer_domain = '';

  console.log('SITE_NAME,', SITE_NAME, nameConfig);

  try {
    // 设置网页标题，这样做避免微信封杀
    console.log(SITE_NAME);
    if (SITE_NAME === 'bw') {
      document.title = nameConfig.welComeText;
    } else {
      if (i_code) {
        document.title =
          Base64.decode(`${nameConfig.welComeText}`) +
          getEnTitleName(nameConfig?.brand) +
          Base64.decode(`${nameConfig.brandName}QXBw`) +
          i_code;
      } else if (r_code) {
        document.title =
          Base64.decode(`${nameConfig.welComeText}`) +
          getEnTitleName(nameConfig?.brand) +
          Base64.decode(`${nameConfig.brandName}QXBw`) +
          r_code;
      } else {
        document.title =
          Base64.decode(`${nameConfig.welComeText}`) +
          getEnTitleName(nameConfig?.brand) +
          Base64.decode(`${nameConfig.brandName}`);
        // 取消QXBw 标题显示了个 欢迎使用69娱乐\
        console.log(
          Base64.decode(`${nameConfig.welComeText}`) +
          getEnTitleName(nameConfig?.brand) +
          Base64.decode(`${nameConfig.brandName}QXBw`)
        );
      }
    }
  } catch (error) {
    uploadErrorInfo('game.setTitle', error, false);
  }

  try {
    // 如果是非移动端用户
    if (!isIOS() && !isAndroid()) {
      let subfix = '';

      if (i_code) {
        subfix = '?i_code=' + i_code;
      } else if (r_code) {
        subfix = '?r_code=' + r_code;
      }
      // 跳转至PC端页面
      if (isSport) {
        // window.location.href = 'downloadty_com.html' + subfix;
      } else {
        // window.location.href = 'download.html' + subfix;
      }

      return;
    }
  } catch (error) {
    uploadErrorInfo('game.forward', error, false);
    return;
  }

  // 初始化 webClip 相关
  function initWebClip() {
    try {
      const fdqInstallBtn = document.querySelector<HTMLElement>('#fdqInstall');
      const isSafari = getBrowserType() === BROWSER.SAFARI;
      const modalType = isSafari
        ? ModalType.ios
        : isIOS()
          ? ModalType.iosNoSafari
          : ModalType.android;
      updateModalContent(modalType);
      if (fdqInstallBtn) {
        fdqInstallBtn.addEventListener('click', () => {
          isCustomer = '';
          isCustomerClick = false;
          updateModalContent(type);
          toAppPostTycm();
          webClipPreUrl = defWebClipUrl;
          setTimeout(() => {
            // 如果是 IOS safari 点击先下载再弹框
            if (modalType === ModalType.ios) {
              modalBtnClick(modalType);
            }
            showModal(modalType);
          }, 500);
        });
      }
    } catch (error) {
      uploadErrorInfo('game.installBtn.click', error, false);
    }
  }

  // 初始化 客服 webClip 相关
  function initCustomerWebClip() {
    try {
      const customerBtn = document.querySelector<HTMLElement>('#consultBtn');
      const isSafari = getBrowserType() === BROWSER.SAFARI;
      const modalType = isSafari
        ? ModalType.ios
        : isIOS()
          ? ModalType.iosNoSafari
          : ModalType.android;
      updateModalContent(modalType);

      // 如果是从 h5/app 跳转过来的直接弹框
      if (isCustomer === '1') {
        const webclipBookMark = isIOS()
          ? ios_webclip_book_mark
          : android_webclip_book_mark;
        webClipPreUrl =
          defKefuWebClipApi +
          '?siteCode=' +
          nameConfig.siteCode +
          '&url=' +
          webclipBookMark;
        showModal(modalType);
      }

      // 点击客服按钮弹框
      if (customerBtn) {
        customerBtn.addEventListener('click', () => {
          isCustomer = '2';
          isCustomerClick = true;
          updateModalContent(type);
          const webclipBookMark = isIOS()
            ? ios_webclip_book_mark
            : android_webclip_book_mark;
          webClipPreUrl =
            defKefuWebClipApi +
            '?siteCode=' +
            nameConfig.siteCode +
            '&url=' +
            webclipBookMark;
          setTimeout(() => {
            // 如果是 IOS safari 点击先下载再弹框
            if (modalType === ModalType.ios) {
              modalBtnClick(modalType);
            }
            showModal(modalType);
          }, 500);
        });
      }
    } catch (error) {
      console.log('---------初始化 客服 webclip 相关失败----------', error);
    }
  }

  function normalInit() {
    const installBtn = document.querySelector<HTMLElement>('#install')!;
    const installDiv = document.querySelector<HTMLElement>('#installDiv');
    // 普通下载
    if (installBtn && installDiv) {
      installBtn.addEventListener('click', function () {
        // 清除桌面客服文字
        isCustomer = '';
        isCustomerClick = false;
        updateModalContent(type);
        try {
          toAppPostTycm();
          installBtn.setAttribute('disabled', 'disabled');
          installDiv.style.display = 'none';
          setTimeout(() => {
            if (isIOS()) {
              // window.location.href = app_ios_download;
              fileUrlHandled(app_ios_download);
            } else {
              window.location.href = app_android_download;
            }
          }, 200);

          installBtn.innerText = nameConfig.nowText + '...';
          setTimeout(function () {
            downloadProgress();
          }, 5000);
        } catch (error) {
          uploadErrorInfo('game.installBtn.click', error, false);
        }
      });
    }
  }

  function initTySCM() {
    try {
      const downloadPanel = document.querySelector<HTMLElement>('#download');
      if (downloadPanel) {
        DomUtil.show(downloadPanel);
        const gotoH5Btn = document.querySelector<HTMLElement>('#gotoH5');
        // 处理下载webclip逻辑
        if (isNeedWebClip() && isIOS()) {
          initWebClip();
        }

        normalInit();

        gotoH5Btn.addEventListener('click', function () {
          const subfix = i_code ? '?i_code=' + i_code : '';
          window.location.href = h5_domain + subfix;
        });
      }
    } catch (error) {
      uploadErrorInfo('game.initTySCM', error, false);
    }
  }

  // 下载上报
  const toAppPostTycm = () => {
    const clipboardInfo = clipboardInfos();
    const data = JSON.stringify({
      ...clipboardInfo,
      startDownloadTime: parseInt(String(new Date().getTime() / 1000), 0),
    });
    const sendData = {
      data,
      device_uid: getCacheUUID(),
      device_uid_ip: `${getCacheUUID()}_${locationIp || ''}`,
    };
    request({
      url: '/api/findmed/v2/jbinstall/submitInfo',
      params: sendData,
      callback: (res: any) => {
        if (res.code === 6000) {
          //
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
      method: 'post',
    });
  };

  function showAppUpdateTips() {
    if (isAppUpdate()) {
      const confirmModal = document.getElementById('confirmModal');
      const modalOverlayTips = document.getElementById('modalOverlayTips');
      if (confirmModal && modalOverlayTips) {
        document.getElementById('confirmModal').style.display = 'block';
        document.getElementById('modalOverlayTips').style.display = 'block';
      }
      const confirmButton = document.getElementById('confirmButton');
      if (confirmButton) {
        confirmButton.addEventListener('click', function () {
          document.getElementById('confirmModal').style.display = 'none';
          document.getElementById('modalOverlayTips').style.display = 'none';
        });
      }
    }
  }

  // 请求前置信息
  function initGetInfo() {
    request({
      url: '/api/findmed/v2/member/preInfo',
      method: 'post',
      params: {},
      callback: (res: any) => {
        if (res.status) {
          const resData = res?.data;
          app_ios_download =
            resData?.site_domain?.app_ios_download || ios_download;
          app_android_download =
            resData?.site_domain?.app_android_download || android_download;
          // 客服 webclip 书签地址
          android_webclip_book_mark =
            resData?.site_domain?.android_webclip_book_mark || '';
          ios_webclip_book_mark =
            resData?.site_domain?.ios_webclip_book_mark || '';
          // 这里循环判断返回的下载地址是否包含i_code或r_code，如果有就替换原来的下载地址
          for (let i = 1; i <= 3; i++) {
            const iosDownload =
              resData?.site_domain[`ios_download_url_${i}`] &&
              JSON.parse(resData?.site_domain[`ios_download_url_${i}`]);
            const androidDownload =
              resData?.site_domain[`android_download_url_${i}`] &&
              JSON.parse(resData?.site_domain[`android_download_url_${i}`]);
            if (
              iosDownload &&
              (iosDownload?.icode === i_code || iosDownload?.icode === r_code)
            ) {
              if (iosDownload?.url) {
                app_ios_download = iosDownload?.url;
              }
            }
            if (
              androidDownload &&
              (androidDownload?.icode === i_code ||
                androidDownload?.icode === r_code)
            ) {
              if (androidDownload?.url) {
                app_android_download = androidDownload?.url;
              }
            }
          }
          if (res?.data?.site_domain?.h5_domain) {
            h5_domain = res?.data?.site_domain?.h5_domain.trim();
          }

          if (
            resData &&
            ((ios_webclip_book_mark && isIOS()) ||
              (android_webclip_book_mark && isAndroid()))
          ) {
            if (isNeedKeFuWebClip()) {
              const serviceCard =
                document.querySelector<HTMLElement>('#serviceCard');
              if (serviceCard) {
                serviceCard.style.display = 'block';
              }
              if (resData?.site_domain?.app_game_download_domain) {
                customer_domain =
                  resData?.site_domain?.app_game_download_domain?.trim() +
                  '/customer.html';
              }

              // customer_domain
              initCustomerWebClip();
            }
          }
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
    });

    request({
      url: '/api/findmed/v2/jbinstall/ip/location',
      params: {},
      callback: (res: any) => {
        if (res.code === 0) {
          locationIp = res?.data?.ip;
          const country = res?.data?.country ?? '';
          const province = res?.data?.province ?? '';
          const city = res?.data?.city ?? '';
          const ipAddressArr = [locationIp, country, province, city];
          ipAddress = JSON.stringify(ipAddressArr);
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
      method: 'post',
    });
  }

  function preloadImage() {
    // 全站图片列表
    const contentList = [
      {
        imgurl: `/resource_images/${imgPath}/download_v2/fullsite_content_page1.png?__static_hash__`,
      },
    ];

    onloadImage(contentList);
  }

  // 皇冠体育横向按钮组初始化
  function initVerticalBtns() {
    const backTopBtn = document.querySelector<HTMLElement>('#backTopBtn');
    if (backTopBtn) {
      backTopBtn.addEventListener('click', function () {
        document.getElementById('introImgBox').scrollIntoView({
          behavior: 'smooth',
        });
      });
    }
    const horizontalBtns =
      document.querySelector<HTMLElement>('#horizontalBtns');
    const gotoH5 = document.querySelector<HTMLElement>('#gotoH5');

    horizontalBtns.style.display = 'flex';
    gotoH5.style.display = 'block';
  }

  // 跳转到h5页面
  function gotoH5Func() {
    const subfix = i_code ? '?i_code=' + i_code : '';
    window.location.href = h5_domain + subfix;
  }

  // app普通下载事件
  function normalInstallFunc() {
    // 清除桌面客服文字
    isCustomer = '';
    isCustomerClick = false;
    updateModalContent(type);
    try {
      toAppPostTycm();
      setTimeout(() => {
        if (isIOS()) {
          fileUrlHandled(app_ios_download);
        } else {
          window.location.href = app_android_download;
        }
      }, 200);
    } catch (error) {
      uploadErrorInfo('game.installBtn.click', error, false);
    }
  }

  console.log(SITE_NAME);
  initCopy();
  initGetInfo();
  initTySCM();
  // showDownloadTips();
  showICode();
  // initSwiper(false);
  // preloadImage();
  initOther();
  initReport();
  // initVerticalBtns();
  showAppUpdateTips();
  // if (SITE_NAME === 'by') {
  //   $('.down_tip').html(
  //     '<li> 需在同一网络环境下下载安装注册，请勿切换网络；<span class="recommend-text"></span></li>'
  //   );
  // }
  return isTencentWebview() ? displayViewGuide() : '';

  function initCopy() {
    // 需要写入剪切板：appKey，设备参数，自定义参数
    const clipboardInfo = clipboardInfos();
    const copyObj = new ClipboardJS('body', {
      text: () => {
        // 写入剪切板的格式：json字符串
        return Base64.encode(JSON.stringify(clipboardInfo));
      },
    });
  }

  /**
   * 第一次上报信息
   *
   */
  function initReport() {
    setTimeout(function () {
      // 刚进来页面时执行第一次日志上报
      const deviceInfo: any = ua2obj();
      if (ipAddress) {
        deviceInfo.ipAddress = ipAddress;
      }
      const query = queryString.parse(window.location.search || '');
      const params = {
        uuid: getCacheUUID(),
        client_type: 'h5',
        device: JSON.stringify(deviceInfo),
        value: JSON.stringify(query),
      };
      request({
        url: '/api/findmed/v2/jbinstall/addAppInfo',
        params,
        callback: (res: any) => {
          //
        },
        fail: (err: any) => {
          console.log(err);
        },
        method: 'post',
      });
    }, 1000);
  }

  /**
   * displayViewGuide 引导
   */
  function displayViewGuide() {
    try {
      const tmpl =
        '<div class="app-guide-mask"><div class="blur"></div><span class="guide-img"></span></div>';

      const appGuideMask = DomUtil.create(tmpl);

      if (appGuideMask) {
        document.body.appendChild(appGuideMask);

        appGuideMask.addEventListener('touchmove', function (event: Event) {
          event.preventDefault();
        });

        appGuideMask.addEventListener('click', function () {
          DomUtil.remove(appGuideMask);
        });
      }
    } catch (error) {
      uploadErrorInfo('game.displayViewGuide', error, false);
    }
  }

  // ----------------  webclicp ----------------------
  // 更新模态框内容  type1: IOS非safari浏览器  type2: IOS 未安装描述文件 type3 安卓下载
  function updateModalContent(type: string) {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const homeUrl = isCustomerClick
      ? `${h5_domain} ${subfix}`
      : customer_domain;
    // 模态框内容配置
    const modalContents = {
      iosNoSafari: {
        imageUrl: `/resource_images/${imgPath}/common/icon_safari.${window.supportWebp ? 'webp' : 'png'
          }?__static_hash__`,
        title: '使用safari浏览器',
        description: '防掉签需要使用safrai下载描 述文件并进行安装。',
        buttonText: '复制域名',
      },
      ios: {
        imageUrl: `/resource_images/${imgPath}/common/icon_seting.${window.supportWebp ? 'webp' : 'png'
          }?__static_hash__`,
        title: `${isCustomer === '2' || isCustomer === '1' ? '桌面客服' : ''
          }安装描述文件`,
        description: '在设置>通用>VPN与设备管理 可见描述文件。',
        buttonText: isCustomer === '1' ? '桌面客服下载' : '重新下载',
      },
      android: {
        imageUrl: '',
        title: '下载到桌面?[如已下载请忽略]',
        description: `如无法正常下载到桌面,请下载【最新版本的Google浏览器】，打开Google浏览器，输入本站网址 ${homeUrl}，点击右上角的【菜单】然后选择【下载到桌面】即可完成WEB版APP`,
        buttonText: '下载到桌面',
      },
    };
    const content = modalContents[type];
    if (content) {
      if (type === ModalType.android) {
        $('#modal img').css('display', 'none');
        $('#modal .modal-title').css('margin-top', '45px');
        $('#modal .modal-title').css('font-size', '20px');
        $('#modal .modal-description').css('font-size', '15px');
      } else {
        $('#modal img').attr('src', content.imageUrl);
      }
      $('#modal .modal-title').text(content.title);
      $('#modal .modal-description').text(content.description);
      $('#modal .modal-button').text(content.buttonText);
    }
  }

  function showModal(type: string) {
    $('#modal-overlay').css('visibility', 'visible');
    $('#modal').css('visibility', 'visible');
    // 显示模态框
    $('#modal-overlay').fadeIn();

    // 关闭模态框
    $('#modal-overlay').click(() => {
      $('#modal-overlay').fadeOut();
    });

    // 关闭模态框 对应弹框 下载/复制按钮事件
    $('#modalButton').click(() => {
      modalBtnClick(type);
      $('#modal-overlay').fadeOut();
    });

    // 阻止modal内部点击事件冒泡
    $('#modal').click((event: Event) => {
      event.stopPropagation();
    });
  }

  function doPromptEvent() {
    if (window.savedPrompt) {
      const promptEvent = window.savedPrompt as any; // 类型断言，因为我们知道 savedPrompt 是什么
      promptEvent.prompt();
      // 等待用户做出响应
      promptEvent.userChoice.then((choiceResult: any) => {
        if (choiceResult.outcome === 'accepted') {
          console.log('用户接受了安装应用');
        } else {
          console.log('用户拒绝了安装应用');
        }
        window.savedPrompt = null;
      });
    }
  }
  function modalBtnClick(type: string) {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const webclipUrl = webClipPreUrl + subfix;
    console.log('不再是standalone模式', window);
    if (type === ModalType.iosNoSafari) {
      initCopyWebClip();
    } else {
      if (type === ModalType.android) {
        doPromptEvent();
      } else {
        // 下载 webclip
        fileUrlHandled(webclipUrl);
      }
    }
  }

  function initCopyWebClip() {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const webclipUrl = `${webClipPreUrl}${subfix}`;

    navigator.clipboard
      .writeText(webclipUrl)
      .then(() => {
        alert('复制成功');
      })
      .catch(() => {
        alert('复制失败');
      });
  }
  // ----------------  webclicp ----------------------

  /**
   * 初始化一些其它的东西
   * 安装引导图、样式微调、IOS额外添加一键信任相关按钮、弹框
   */
  function initOther() {
    try {
      window.supportWebp =
        document
          .createElement('canvas')
          .toDataURL('image/webp')
          .indexOf('data:image/webp') === 0
          ? true
          : false;
    } catch (err) {
      window.supportWebp = false;
    }
    try {
      const installTutorial =
        document.querySelector<HTMLElement>('#installTutorial');
      const remind = document.querySelector<HTMLElement>('.remind');
      let imgUrl = '';
      let imgLogoUrl = '';
      const logo_img = document.querySelector<HTMLElement>(
        '.logo_box .logo_right_img'
      );
      if (logo_img) {
        logo_img.setAttribute(
          'src',
          `/resource_images/${imgPath}/download_v2/content_logo_new.png?__static_hash__`
        );
      }
      // const logo_title_img = document.querySelector<HTMLElement>(
      //   '.logo_box .logo_desc_img'
      // );
      // if (logo_title_img) {
      //   logo_title_img.setAttribute(
      //     'src',
      //     `/resource_images/${imgPath}/download_v2/fullsite_content_page2.${window.supportWebp ? 'webp' : 'png'
      //     }?__static_hash__`
      //   );
      // }
      const tuto = document.querySelector<HTMLElement>('#tuto');
      const torial = document.querySelector<HTMLElement>('#torial');
      if (isAndroid()) {
        const downTips = document.querySelector<HTMLElement>('.down_tip');

        if (remind) {
          remind.classList.add('android');
          remind.style.minHeight = '100%';
        }
        if (tuto) {
          tuto.innerHTML = '';
        }
      } else {
        imgUrl = `/resource_images/${imgPath}/download_v2/fullsite_content.png?__static_hash__`;
        imgLogoUrl = `/resource_images/${imgPath}/download_v2/apple.${window.supportWebp ? 'webp' : 'png'
          }?__static_hash__`;
        const modalWrap = DomUtil.create<HTMLElement>(
          '<div class="modal_wrap"><div class="modal_box"><p>一键信任只支持 Safari 浏览器哦~  </p><p>请下滑查看手动信任教程。</p><button id="hideMOdal">确认</button></div></div>'
        );
        if (remind) {
          remind.classList.remove('android');
        }
        if (modalWrap) {
          document.body.appendChild(modalWrap);

          modalWrap.addEventListener('click', function () {
            DomUtil.hide(modalWrap);
          });
        }

        nameConfig.showTorial;

        if (nameConfig.showTorial) {
          if (tuto) {
            tuto.style.display = 'block';
          }

          if (torial) {
            torial.style.display = 'block';
          }
        }
      }

      if (installTutorial) {
        installTutorial.setAttribute('src', imgUrl);
      }
    } catch (error) {
      uploadErrorInfo('game.initOther', error, false);
    }
  }

  function getProgressBarColo(brand: string) {
    const res = {
      color: '#ceb89f',
      trailColor: '#e6e1dc',
    };
    switch (brand) {
      case '10004':
        res.color = '#2043E4';
        res.trailColor = '#E6E1DC';
        break;
      case '10005':
        res.color = '#2043E4';
        res.trailColor = '#E6E1DC';
        break;
      default:
        break;
    }
    return res;
  }

  /**
   * 下载开始假的进度条
   *
   */
  function downloadProgress() {
    const installBtn = document.querySelector<HTMLElement>('#install');
    const trustElem = document.querySelector<HTMLElement>('#trust');
    const progress = document.querySelector<HTMLElement>('#progress');
    const progressContainer =
      document.querySelector<HTMLElement>('#progressContainer');
    let timer;
    let i = 30;
    const bar = new ProgressBar.Circle(progress, {
      strokeWidth: 5,
      easing: 'linear',
      duration: 1500,
      color: getProgressBarColo(nameConfig.brand).color,
      trailColor: getProgressBarColo(nameConfig.brand).trailColor,
      trailWidth: 5,
      svgStyle: null,
      step: (state, circle) => {
        const value = Math.round(circle.value() * 100);
        circle.setText(value + '%');
      },
    });
    // 下载时隐藏下载完成按钮 显示进度条及信任按钮
    if (installBtn && progressContainer) {
      installBtn.style.display = 'none';
      progressContainer.style.display = 'flex';
    }
    // 如果是安卓显示正在下载
    if (isAndroid()) {
      (trustElem as any).innerText = nameConfig.nowText + '...';
    }
    clearInterval(timer);
    timer = setInterval(() => {
      task();
    }, 1000);

    function task() {
      try {
        if (i <= 0) {
          bar.animate(1);
          setTimeout(() => {
            downloadComplete();
          }, 1500);
          clearInterval(timer);
          timer = null;
        } else {
          i--;

          if (Math.random() > 0.3 && installBtn) {
            const num = Math.floor(((30 - i) / 30) * 100);
            bar.animate(num / 100);
          }
        }
      } catch (error) {
        uploadErrorInfo('game.downloadProgress', error, false);
      }
    }
  }

  /**
   * IOS进度条读完后处理
   *
   */
  function downloadComplete() {
    try {
      const installBtn = document.querySelector<HTMLElement>('#install');
      const installDiv = document.querySelector<HTMLElement>('#installDiv');
      const confirmCompletedElem =
        document.querySelector<HTMLElement>('.confirm_completed');
      const trustElem = document.querySelector<HTMLElement>('#trust');

      if (installBtn && installDiv) {
        installBtn.setAttribute('disabled', 'disabled');
        installDiv.style.display = 'none';
        const Button: any = isAndroid() ? trustElem : installBtn;
        DomUtil.addClass(Button, 'install_end');
        Button.innerHTML = `<img src="/resource_images/${imgPath}/common/icon_dui.${window.supportWebp ? 'webp' : 'png'
          }?__static_hash__"><span>${nameConfig.successText}</span>`;
      }
      if (isIOS()) {
        if (confirmCompletedElem) {
          confirmCompletedElem.innerText =
            '请确认APP下载完成后，再点击“一键信任”';
        }
        if (trustElem) {
          DomUtil.addClass(trustElem, 'trust_active');
          trustElem.addEventListener('click', function () {
            window.location.href = `/resource_images/${imgPath}/common/open.mobileprovision`;
          });
          trustElem.removeAttribute('disabled');
        }
      }
    } catch (error) {
      uploadErrorInfo('game.downloadComplete', error, false);
    }
  }

  /**
   * 展示下载的友好提示
   *
   */
  function showDownloadTips() {
    try {
      // 执行相关dom操作相关函数
      const elem = document.querySelector('.recommend-text');
      const elemGotoH5 = document.querySelector('.gotoH5');
      const eleTutoTxt = document.querySelector('.tutoTxt');

      if (elem) {
        // 设置浏览器文案提示
        if (isAndroid()) {
          elem.innerHTML = nameConfig.andrindRecommendText;
        } else {
          elem.innerHTML = nameConfig.iosRecommendText;
        }

        elemGotoH5.innerHTML = nameConfig.gotoH5Text;
        eleTutoTxt.innerHTML = nameConfig.tutoText;
      }
    } catch (error) {
      uploadErrorInfo('game.showDownloadTips', error, false);
    }
  }

  /**
   * 展示ICode
   *
   */
  function showICode() {
    try {
      if (i_code) {
        // 设置i_code字段
        const iCodePanel = document.querySelector<HTMLElement>('#show_i_code');

        if (iCodePanel) {
          iCodePanel.innerText = i_code === 'nobody' ? '' : i_code;
        }
      } else if (r_code) {
        // 设置r_code字段
        const iCodePanel = document.querySelector<HTMLElement>('#show_i_code');

        if (iCodePanel) {
          iCodePanel.innerText = r_code === 'nobody' ? '' : r_code;
        }
      }
    } catch (error) {
      uploadErrorInfo('game.showICode', error, false);
    }
  }

  /**
   * 初始化Swiper
   *
   */
  function slideChangeCb(el) {
    // @ts-ignore
    const that: any = this;
    const prevItemImg = that.slides.find(el);
    const activityItemImg = that.slides.eq(that.activeIndex).find(el);
    prevItemImg.transform('scale(0.5, 0.5)').css('opacity', '0');
    activityItemImg.css('opacity', '1').transform(' scale(1, 1)');
  }
  function slideChangeTransitionEndCB(el) {
    // @ts-ignore
    const that: any = this;
    that.slides
      .eq(that.previousIndex)
      .find(el)
      .transform('scale(0.5, 0.5)')
      .css('opacity', '0');
  }
  /**

   */
  function initSwiper(themes?: boolean) {
    try {
      const pagination = null;
      const mySwiper = new Swiper('.swiper-container', {
        init: false,
        speed: 700,
        loop: false,
        touchRatio: 2,
        followFinger: false,
        longSwipes: true,
        longSwipesMs: 3000,
        longSwipesRatio: 0.1,
        threshold: 4,

        resistance: false,
        pagination,
        lazy: {
          loadOnTransitionStart: true,
          elementClass: 'swiper-lazy',
        },
        on: {
          slideChange() {
            (slideChangeCb as any).call(this, 'img');
            (slideChangeCb as any).call(this, '.imgCon');
          },
          slideChangeTransitionEnd() {
            const that: any = this;
            (slideChangeTransitionEndCB as any).call(this, 'img');
            (slideChangeTransitionEndCB as any).call(this, 'imgCon');
          },
        },
      });

      // 全站轮播
      let siteSwiperList = `
        <div class="swiper-slide">
        <div class="imgCon" style="opacity: 1; transform: scale(1, 1)">
          <img src="/resource_images/${imgPath}/download_v2/fullsite_content_page1.png?__static_hash__" style="opacity: 1; transform: scale(1, 1)" />
         </div>
      </div>`;

      mySwiper.appendSlide(siteSwiperList);
      mySwiper.init();
    } catch (error) {
      uploadErrorInfo('game.initSwiper', error, false);
    }
  }
}
function clipboardInfos(): any {
  // 提取url参数
  const urlParams = qs.parse(window.location.search, {
    ignoreQueryPrefix: true,
  });
  const platform = isIOS() ? 'ios' : 'android';
  // 需要写入剪切板：appKey，设备参数，自定义参数
  const clipboardInfo = Object.assign({
    data: urlParams,
    url: location.href,
    hasData: Object.keys(urlParams).length > 0 ? 1 : 0,
    screen: window.screen.width * window.screen.height, // 屏幕宽高得出的积
    platform, // 平台类型
  });

  return clipboardInfo;
}
